﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Xml;
using System.Xml.Linq;

namespace Copy5x
{
    public class Copy
    {
        DirectoryInfo DestFolder;
        DirectoryInfo SourceFolder;
        ErrorLog ErrLog;

        public Copy(string sourceFolder, string destFolder)
        {
            SourceFolder = new DirectoryInfo(sourceFolder);

            if (!SourceFolder.Exists)
            {
                Logger.Log("Source Folder Not Found", LogType.Error, false);             
            }
            else
            {
                try
                {
                    DestFolder = new DirectoryInfo(destFolder);
                    
                    ChkNCreateFolder(DestFolder);
                    ErrLog = new ErrorLog(DestFolder.FullName); 

                    CopyAll(SourceFolder, DestFolder);
                }
                catch (Exception exp)
                {                    
                    Logger.Log(exp);
                }
            }
        }

        private void CopyAll(DirectoryInfo src, DirectoryInfo dest)
        {
            ChkNCreateFolder(dest);

            foreach (FileInfo file in src.GetFiles())
            {
                try
                {
                    Logger.Log("Copying : " + file.FullName);
                    file.CopyTo(dest.FullName + Path.DirectorySeparatorChar + file.Name);
                }
                catch(Exception exp)
                {
                    Logger.Log("Copy failed for : " + file.FullName, LogType.Error, false);
                    Logger.Log(exp);
                    ErrLog.AddError(file.FullName, exp.ToString());
                }
            }

            foreach (DirectoryInfo subFolder in src.GetDirectories())
            {
                CopyAll(subFolder, new DirectoryInfo(dest.FullName + Path.DirectorySeparatorChar  + subFolder.Name) ); 
            }

        }

        private void ChkNCreateFolder(DirectoryInfo folder)
        {
            if (!folder.Exists)
            {
                try
                {
                    Logger.Log("Creating new folder : " + folder.FullName);
                    folder.Create();
                }
                catch (Exception exp)
                {
                    Logger.Log("Creating new folder failed for : " + folder.FullName, LogType.Error, false);
                    Logger.Log(exp);
                }
            }  
        }
    }
}
